import Head from 'next/head';
import React,{ useReducer} from "react";
import ProductCard from '../components/ProductCard/ProductCard.tsx';
import PayCenter from '../components/PayCenter/PayCenter.tsx';
const reducer = (state, action) => {
  switch (action.type) {
    case 'add':
      var products  = JSON.parse(JSON.stringify(state.products));
      const { product } = action;
      const productIDs = products.map(item => item.id);
      if (!productIDs.includes(product.id)) {
        console.log(product,9999)
        products.push({ ...product, num: 1 });
      } else {
        products = products.map(item => {
          if (item.id === product.id) {
            item.num += 1;
          }
          return item;
        })
      }
      return {products }
    case "delete":
      return {products: state.products.filter(item => item.id !== action.id) }
  }

}
export default function Home() {

  const products = [{
    id: 1,
    name: "苹果",
    price: '10.00'
  }, {
    id: 2, name: "香蕉", price: '20.00'
  }, { id: 3, name: '香蕉香蕉香蕉香蕉香蕉香蕉香蕉香蕉香蕉香蕉香蕉', price: '30.00' }];
  const store = {
    products: []
  };
  const [state, dispatch] = useReducer(reducer, store);
  const add = ({ id, price, name }) => {
    dispatch({ type: "add", product: { id, price, name,num:1 } })
  }
  const deleteAll = (id) => {
    dispatch({ type: "delete", id })

  }
  return (
      <div className="container">
        <Head>
          <title>购物天堂</title>
          <link rel="icon" href="/favicon.ico" />
        </Head>

        <main className='center'>
          {products.map(product => <ProductCard key={product.id} {...product} add={add} deleteAll={deleteAll} />)}
        </main>
        <footer>
          <PayCenter products={state?.products || []} deleteAll={deleteAll} />
        </footer>
        <style jsx>{`
      .center{
        display: flex;
        justify-content: center;
        align-items: center;
      }
      `}</style>
      </div>
  )
}
